package de.tudarmstadt.ukp.muip.fibqdojo.io.raw;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.google.common.collect.Lists;

import de.tudarmstadt.ukp.muip.fibqdojo.Sentence;
import de.tudarmstadt.ukp.muip.fibqdojo.interfaces.IFIBQSentence;
import de.tudarmstadt.ukp.muip.fibqdojo.interfaces.IFIBQSentenceToken;
import de.tudarmstadt.ukp.muip.fibqdojo.io.Reader;

public class RawSentenceReader extends Reader {

    private final String path;

    private final int limit;
    
    public RawSentenceReader(String path) {
        this.path = path;
        this.limit = -1;
    }

    public RawSentenceReader(String path, int limit) {
        this.path = path;
        this.limit = limit;
    }

    public List<IFIBQSentence> read() throws ParserConfigurationException, SAXException, IOException {
        List<IFIBQSentence> sentences = Lists.newArrayList();
        NodeList rawSentences = getTopHierarchyData(new File(path), SENTENCE);
        for (int i = 0; i < rawSentences.getLength(); i++) {

            if (limitReached(i)) {
                return sentences;
            }

            Node xmlSentence = rawSentences.item(i);
            sentences.add(processSentence(xmlSentence));
        }
        return sentences;
    }

    private boolean limitReached(int i) {
        return limit != -1 && i == limit;
    }

    private IFIBQSentence processSentence(Node xmlSentence) {

        List<IFIBQSentenceToken> processSentence = null;

        int kind = getSentenceKind(xmlSentence);
        switch (kind) {
        case 1:
            TokenReader tokenReader = new TokenReader(xmlSentence);
            processSentence = tokenReader.processSentence();
            return new Sentence(processSentence.toArray(new IFIBQSentenceToken[0]));
        case 2:
            JapaneseTokenReader japaneseTokenReader = new JapaneseTokenReader(xmlSentence);
            processSentence = japaneseTokenReader.processSentence();
            return new Sentence(processSentence.toArray(new IFIBQSentenceToken[0]));
        }

        throw new IllegalArgumentException("The sentence kind with number '" + kind + "' is unknown");
    }

    private int getSentenceKind(Node xmlSentence) {
        NamedNodeMap attributes = xmlSentence.getAttributes();
        Node namedItem = attributes.getNamedItem("kind");
        return Integer.parseInt(namedItem.getNodeValue());
    }
}
